import random
def create_address(country,province,street,house_number):
    return{
        "country":country,
        "province":province,
        "street":street,
        "house_number":house_number
    }
def create_user(account_id,name,password,address,balance):
    account_id_str = str(account_id).zfill(8)
    password_int = int(str(password).zfill(6)[:6])
    return{
        "account_id": account_id_str,
        "name": name,
        "password": password_int,
        "address": address,
        "balance": balance,
        'bank_name':'中国工商银行'
    }
def create_bank(max_users=100):
    return{
        'name':'中国工商银行',
        'users':{},
        'max_users':max_users
    }
def generate_account_id(bank):
    while True:
        account_id = str(random.randint(10000000,99999999))
        if account_id not in bank['users']:
            return account_id
def add_user(bank,user_info):
    if len(bank['users'])>=bank['max_users']:
        return 3
    account_id = user_info['account_id']
    if account_id in bank['users']:
        return 2
    address = create_address(
        user_info['country'],
        user_info['province'],
        user_info['street'],
        user_info['house_number']
    )
    user = create_user(
        account_id,
        user_info['name'],
        user_info['password'],
        address,
        user_info['balance']
    )
    bank['users'][account_id] = user
    return 1
def deposit(bank,account_id,amount):
    if account_id not in bank['users'] or amount<= 0:
        return False
    bank['users'][account_id]['balance'] += amount
    return True
def withdraw(bank,account_id,password,amount):
    if account_id not in bank['users']:
        return 1
    user = bank['users'][account_id]
    if user['password'] != password:
        return 2
    password = user['password']
    if amount<=0 or user['balance']<amount:
        return 3
    user['balance'] -=amount
    return 0
def transfer(bank,from_account,to_account,password,amount):
    if from_account not in bank['users'] or to_account not in bank['users']:
        return 1
    user = bank['users'][from_account]
    if user['password'] != password:
        return 2
    password = user['password']
    if amount<=0 or user['balance']<amount:
        return 3
    bank['users'][from_account]['balance'] -= amount
    bank['users'][to_account]['balance'] += amount
    return 0
def query_account(bank,account_id,password):
    if account_id not in bank['users']:
        print("该用户不存在")
        return
    user = bank['users'][account_id]
    if user['password'] != password:
        print("密码不正确")
        return
    password = user['password']
    address = user['address']
    address_str = f"{address['country']}{address['province']}{address['street']}{address['house_number']}"
    print(f"当前账号：{user['account_id']},姓名:{user['name']},密码:{user['password']},"
          f"余额:{user['balance']}元,用户居住地址：{address_str},"
          f"当前账号的开户行：{user['bank_name']}")
def print_menu():
        print("*" * 38)
        print("*      中国工商银行                    *")
        print("*      账号管理系统                    *")
        print("*         V1.0                       *")
        print("*" * 38)
        print("*1.开户                               *")
        print("*2.存钱                               *")
        print("*3.取钱                               *")
        print("*4.转账                               *")
        print("*5.查询                               *")
        print("*6.Bye！                              *")
        print("*" * 38)
def get_valid_account_id(prompt, bank=None, check_existence=False):
    """获取有效的账号输入"""
    while True:
        account_id = input(prompt).strip()
        # 检查账号是否为8位数字
        if len(account_id) == 8 and account_id.isdigit():
            # 如果需要检查账号是否存在
            if check_existence and bank is not None:
                if account_id in bank['users']:
                    return account_id
                else:
                    print("账号不存在，请重新输入！")
            else:
                return account_id
        else:
            print("账号必须是8位数字，请重新输入！")

def get_valid_password(prompt):
    """获取有效的密码输入"""
    while True:
        password = input(prompt).strip()
        if len(password) == 6 and password.isdigit():
            return int(password)
        else:
            print("密码必须是6位数字，请重新输入！")

def get_valid_amount(prompt):
    """获取有效的金额输入"""
    while True:
        amount_str = input(prompt).strip()
        if amount_str.isdigit():
            amount = int(amount_str)
            if amount > 0:
                return amount
            else:
                print("金额必须大于0，请重新输入！")
        else:
            print("金额必须是正整数，请重新输入！")

def main():
    # 创建银行（名称固定为中国工商银行）
    bank = create_bank()

    while True:
        print_menu()
        # 获取并验证用户选择
        while True:
            choice = input("请选择业务(1-6)：").strip()
            if choice in ['1', '2', '3', '4', '5', '6']:
                break
            else:
                print("无效的选择，请输入1-6之间的数字！")

        if choice == '1':
            # 开户（账号由系统生成，不允许用户输入）
            if len(bank['users']) >= bank['max_users']:
                print("抱歉，用户库已满，无法开户！")
                input("\n按回车键继续...")
                continue

            # 系统自动生成账号并显示
            account_id = generate_account_id(bank)
            print(f"系统为您生成的账号是：{account_id}（不可修改）")

            # 收集用户输入信息（不含账号和开户行）
            while True:
                name = input("请输入姓名：").strip()
                if name:  # 确保姓名不为空
                    break
                print("姓名不能为空，请重新输入！")

            # 获取有效的密码
            password = get_valid_password("请设置6位数字密码：")

            # 收集地址信息
            while True:
                country = input("请输入国家：").strip()
                if country:
                    break
                print("国家不能为空，请重新输入！")

            while True:
                province = input("请输入省份：").strip()
                if province:
                    break
                print("省份不能为空，请重新输入！")

            while True:
                street = input("请输入街道：").strip()
                if street:
                    break
                print("街道不能为空，请重新输入！")

            while True:
                house_number = input("请输入门牌号：").strip()
                if house_number:
                    break
                print("门牌号不能为空，请重新输入！")

            # 获取有效的初始存款
            while True:
                balance_str = input("请输入初始存款金额：").strip()
                if balance_str.isdigit():
                    balance = int(balance_str)
                    if balance >= 0:
                        break
                    else:
                        print("存款金额不能为负数！")
                else:
                    print("请输入有效的数字！")

            # 准备用户信息（包含系统生成的账号）
            user_info = {
                'account_id': account_id,
                'name': name,
                'password': password,
                'country': country,
                'province': province,
                'street': street,
                'house_number': house_number,
                'balance': balance
            }

            # 添加用户
            result = add_user(bank, user_info)
            if result == 1:
                print("开户成功！")
            elif result == 2:
                print("该账号已存在，开户失败！")
            elif result == 3:
                print("用户库已满，开户失败！")

        elif choice == '2':
            # 存钱
            account_id = get_valid_account_id("请输入账号：", bank, check_existence=True)
            amount = get_valid_amount("请输入存款金额：")

            if deposit(bank, account_id, amount):
                print(f"存款成功！当前余额：{bank['users'][account_id]['balance']}元")
            else:
                print("存款失败，账号不存在或金额无效！")

        elif choice == '3':
            # 取钱
            account_id = get_valid_account_id("请输入账号：", bank, check_existence=True)
            password = get_valid_password("请输入密码：")
            amount = get_valid_amount("请输入取款金额：")

            result = withdraw(bank, account_id, password, amount)
            if result == 0:
                print(f"取款成功！当前余额：{bank['users'][account_id]['balance']}元")
            elif result == 1:
                print("账号不存在！")
            elif result == 2:
                print("密码不正确！")
            elif result == 3:
                print("余额不足！")

        elif choice == '4':
            # 转账
            from_account = get_valid_account_id("请输入转出账号：", bank, check_existence=True)
            to_account = get_valid_account_id("请输入转入账号：", bank, check_existence=True)
            password = get_valid_password("请输入转出账号密码：")
            amount = get_valid_amount("请输入转账金额：")

            result = transfer(bank, from_account, to_account, password, amount)
            if result == 0:
                print(f"转账成功！您的当前余额：{bank['users'][from_account]['balance']}元")
            elif result == 1:
                print("转出或转入账号不存在！")
            elif result == 2:
                print("密码不正确！")
            elif result == 3:
                print("余额不足！")

        elif choice == '5':
            # 查询
            success = False
            while not success:
                account_id = get_valid_account_id("请输入账号：")
                password = get_valid_password("请输入密码：")
                success = query_account(bank, account_id, password)
                if success:
                    print("查询成功！")
                    break
                if not success:
                    retry = input("是否重新输入？(y/n)：").strip().lower()
                    if retry != 'y':
                        break

        elif choice == '6':
            # 退出
            print("感谢使用，再见！")
            break

        input("\n按回车键继续...")


if __name__ == "__main__":
    main()
